import { useMysql } from "../mysql/index.js";
import { MysqlQueryBuilder } from "../mysql/mysql-query-builder.js";
import { formatDate } from "../utils/timeDajs.js";
// 查询所有用户数据
export const getUserAll = async (req, res) => {
  const sql = MysqlQueryBuilder.select("users");
  try {
    const result = await useMysql(sql);
    res.status(200).send({
      code: 200,
      message: "查询成功",
      data: result,
    });
  } catch (err) {
    console.error("查询失败:", err);
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};
// 分页查询用户
export const getUsersArr = async (req, res) => {
  const { page, pageSize } = req.body;
  const { rowSql, countSql } = await MysqlQueryBuilder.paginate(
    "users",
    ["id", "Name", "username", "password", "phoneA", "email", "status"],
    {},
    page,
    pageSize
  );
  try {
    // 执行查询
    const [rowResult, countResult] = await Promise.all([
      useMysql(rowSql),
      useMysql(countSql),
    ]);
    const total = countResult[0].total;
    const totalPages = Math.ceil(total / pageSize);
    return res.json({
      code: 200,
      row: rowResult,
      total: total,
      message: "Success",
    });
  } catch (error) {
    return res.status(404).json({
      code: 404,
      message: "File not found",
    });
  }
};
// 更新用户
export const updataUserById = async (req, res) => {
  const { id, Name, username, password, phoneA, email, status } = req.body;
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.update(
    "users",
    {
      password: password,
      phoneA: phoneA,
      email: email,
      status: status,
    },
    {
      id: id,
    }
  );
  try {
    await useMysql(sql);
    res.status(200).send({
      code: 200,
      message: "修改成功",
    });
  } catch (err) {
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};
// 删除用户(单id)
export const deleteUserById = async (req, res) => {
  const userId = parseInt(req.params.id);
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.delete("users", {
    id: userId,
  });
  try {
    await useMysql(sql);
    res.status(200).send({
      code: 200,
      message: "删除成功",
    });
  } catch (err) {
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};
// 删除用户(多id批量)
export const deleteUserMoreById = async (req, res) => {
  const ids = req.body;
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.delete("users", {
    id: ids,
  });
  try {
    await useMysql(sql);
    res.status(200).send({
      code: 200,
      message: "删除成功",
    });
  } catch (err) {
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};

// 查找用户(单条件)
export const SearchUserKey = async (req, res) => {
  const { SearchKey, SearchValue, page, pageSize } = req.body;
  // 中间转化
  const TemObject = {};
  TemObject[SearchKey] = SearchValue;
  const { rowSql, countSql } = await MysqlQueryBuilder.paginate(
    "users",
    ["*"],
    TemObject,
    page,
    pageSize
  );
  try {
    // 执行查询
    const [rowResult, countResult] = await Promise.all([
      useMysql(rowSql),
      useMysql(countSql),
    ]);
    const total = countResult[0].total;
    const totalPages = Math.ceil(total / pageSize);
    return res.json({
      code: 200,
      row: rowResult,
      total: total,
      message: "Success",
    });
  } catch (error) {
    return res.status(404).json({
      code: 404,
      message: "File not found",
    });
  }
};

// 指定id连表查询
export const SelectMybyId = async (req, res) => {
  const id = parseInt(req.params.id);
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.join(
    "users", // 主表名
    [
      {
        table: "roles",
        alias: "r",
        on: "users.role_id = r.role_id",
        type: "INNER",
      },
    ],
    ["*"],
    { id: id },
    {}
  );
  try {
    const result = await useMysql(sql);
    // 时间处理
    result[0].sign_date = formatDate(result[0].sign_date);
    res.status(200).send({
      code: 200,
      message: "查询成功",
      data: result,
    });
  } catch (err) {
    console.error("查询失败:", err);
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};
// 用户头像上传
export const upUserImg = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ code: 400, message: "无文件上传" });
    }
    const { path, filename } = req.file;
    const id = req.headers["x-user-id"];
    // 使用MysqlQueryBuilder构建更新语句
    const upSql = MysqlQueryBuilder.update(
      "users",
      {
        avatarimg: path,
      },
      {
        id: id,
      }
    );
    // 执行SQL
    const result = await useMysql(upSql);

    res.json({
      code: 200,
      data: {
        id: id,
        filename,
        path,
      },
      message: "头像上传成功",
    });
  } catch (error) {
    console.error("Upload error:", error);
    res.status(500).json({ code: 500, message: "Server error" });
  }
};
// 基本信息更新
export const updataBaseUserById = async (req, res) => {
  const {
    id,
    Name,
    username,
    password,
    age,
    gender,
    IDcard,
    phoneA,
    email,
    status,
    address,
    notes,
    phoneB,
    introduce,
  } = req.body;
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.update(
    "users",
    {
      password: password,
      age: age,
      gender: gender,
      IDcard: IDcard,
      phoneA: phoneA,
      email: email,
      status: status,
      address: address,
      notes: notes,
      phoneB: phoneB,
      introduce: introduce,
    },
    {
      id: id,
    }
  );
  try {
    await useMysql(sql);
    res.status(200).send({
      code: 200,
      message: "修改成功",
    });
  } catch (err) {
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};
// 更新用户职业经历
export const updataEcxUserById = async (req, res) => {
  const { id, experience } = req.body;
  // 构造 SQL 查询语句
  const sql = MysqlQueryBuilder.update(
    "users",
    {
      experience: experience,
    },
    {
      id: id,
    }
  );
  try {
    await useMysql(sql);
    res.status(200).send({
      code: 200,
      message: "修改成功",
    });
  } catch (err) {
    res.status(500).send({
      code: 500,
      message: "服务器内部错误",
    });
  }
};